module.exports = class extends saas.Service {
  async checkPermission(roleId, url, appId = null) {
    if (url.indexOf('?') >= 0) {
      url = url.split('?')[0];
    }
    
    const whiteList = [
      '/permission/getMenu'
    ]
    for (const white of whiteList) {
      if (white == url) {
        return true;
      }
    }
    const permission = await this.getPermissionByRole(roleId);
    if (saas.isEmpty(permission)) {
      return false;
    }
    const apiData = permission.apiData;
    for (const api of apiData) {
      if (api.url == url) {
        return true;
      }
    }
    return false;
  }
  
  async getMenu(roleId,appId = null) {
    const permission = await this.getPermissionByRole(roleId,appId);
    if (permission) {
      return permission.menuData;
    } else {
      return null;
    }
  }
  
  async getPermissionByRole(roleId,appId = null) {

    return await saas.cache(`role_permission_${roleId}`, async () => {
      const menuGroupIds = (await this.mysql(this.tableName('role')).where({id: roleId}).select('menu_group_ids').first()).menu_group_ids || '';
      const menuIds = await this.mysql(this.tableName('menu_group')).whereIn('id', menuGroupIds.split(',')).select('menu_ids');
      if (!saas.isEmpty(menuIds)) {
        const menuIdArr = [];
        for (const menu of menuIds) {
          if (menu.menu_ids) {
            menu.menu_ids = menu.menu_ids.split(',');
            menuIdArr.push(...menu.menu_ids);
          }
        }
        const menuList = await this.mysql(this.tableName('menu')).whereIn('id', menuIdArr);
        const menuData = menuList.filter(p => p.is_menu === 1);
        menuData.forEach(menu => {
          if (saas.isEmpty(menu.parent_id)) {
            menu.children = menuData.filter(p => p.parent_id === menu.id);
          }
        })
        
        return {
          menuData: menuData.filter(p => saas.isEmpty(p.parent_id)),
          apiData: menuList.filter(p => p.is_action === 1)
        }
      } else {
        return null;
      }
    }, 1000 * 1);
  }

  async getAppList(adminId) {
    const appIds = await this.model('adminApp').getAppIds(adminId);
    const apps = await this.model('app').getAppByIds(appIds);
    return apps;
  }
}